/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function (head, k) {
  // let tail = head
  // let len = 1
  // if (head) {
  //   while (tail.next) {
  //     len++
  //     tail = tail.next
  //   }
  //   tail.next = head
  //   for (let i = 0; i < len - k % len; i++) {
  //     head = head.next
  //     tail = tail.next
  //   }
  //   tail.next = null
  // }
  // return head




  let tail = head
  if (head) {
    let len = 1
    while (tail.next) {
      len++
      tail = tail.next
    }

    tail.next = head

    while ((len - (k % len)) != 0) {
      head = head.next
      tail = tail.next
      k++
    }
    tail.next = null
  }
  return head
};

let l = {
  val: 1,
  next: {
    val: 2,
    next: {
      val: 3,
      next: {
        val: 4,
        next: {
          val: 5,
          next: null
        }
      }
    }
  }
}


rotateRight(l, 2)